package com.godenwater.web.task;

import com.aliyuncs.exceptions.ClientException;
import com.godenwater.core.spring.Application;
import com.godenwater.core.spring.BaseDao;
import com.godenwater.framework.config.SpringUtils;
import com.godenwater.recv.RecvConstant;
import com.godenwater.recv.decode.Sl651MessageDecoder;
import com.godenwater.recv.decode.YanyuMessageDecoder;
import com.godenwater.recv.decode.YlnMessageDecoder;
import com.godenwater.recv.model.CommonMessage;
import com.godenwater.recv.service.*;
import com.godenwater.recv.spring.Configurer;
import com.godenwater.utils.ByteUtils;
import com.godenwater.utils.Server;
import com.godenwater.utils.SmsUtil;
import com.godenwater.web.manager.StationManager;
import com.godenwater.web.rtu.model.RtuHourData;
import com.godenwater.web.rtu.model.RtuStationModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

public class TimeTask {
    private Logger logger = LoggerFactory.getLogger(TimeTask.class);
    private RedisTemplate redisTemplate;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private BaseDao baseReadDao;
    private BaseDao baseDao;

    public void handlerUpdateYySt() {
        if (baseReadDao == null) {
            baseReadDao = SpringUtils.getBean("baseReadDao");
        }
        logger.debug(">> 读取测站基本信息 添加到redis！" + formatter.format(new Date()));
        String sqlStation = "select * from rtu_station";
        List<Map<String, Object>> stations = baseReadDao.getJdbcTemplate().queryForList(sqlStation);
        redisTemplate = SpringUtils.getBean("redisTemplate");
        ValueOperations station = redisTemplate.opsForValue();
        station.set("station", stations);
    }

    public void handlerUpdateSt() {
        if (baseReadDao == null) {
            baseReadDao = SpringUtils.getBean("baseReadDao");
        }
        try {
            redisTemplate =  SpringUtils.getBean("redisTemplate");
            logger.debug(">> 更新测站缓存数据！" + new Date());
            String sql = "select * from rtu_station a ";

            List<RtuStationModel> stationList = baseReadDao.getJdbcTemplate().query(sql, new RowMapper<RtuStationModel>() {

                public RtuStationModel mapRow(ResultSet rs, int rowNum)
                        throws SQLException {
                    RtuStationModel station = new RtuStationModel();
                    station.setStcd(rs.getString("STCD"));
                    station.setStcd8(rs.getString("STCD8"));
                    station.setCodetype(rs.getString("CODETYPE"));
                    station.setStlc(rs.getString("STLC"));
                    station.setStnm(rs.getString("STNM"));
                    station.setSttp(rs.getString("STTP"));
                    station.setBsnm(rs.getString("BSNM"));
                    station.setRvnm(rs.getString("RVNM"));
                    station.setHnnm(rs.getString("HNNM"));
                    station.setLgtd(rs.getString("LGTD"));
                    station.setLttd(rs.getString("LTTD"));
                    station.setProtocol(rs.getString("PROTOCOL"));
                    station.setMsgmode(rs.getString("MSGMODE"));
                    station.setWorkmode(rs.getString("WORKMODE"));
                    station.setProject(rs.getString("PROJECT"));
                    station.setSupply(rs.getString("SUPPLY"));
                    station.setAddvcd(rs.getString("ADDVCD"));
                    station.setAdmauth(rs.getString("ADMAUTH"));
                    station.setRtucd(rs.getString("RTUCD"));
                    station.setDtmel(rs.getBigDecimal("DTMEL"));
                    station.setRainValidDay(rs.getBigDecimal("RAIN_VALID_DAY"));
                    station.setRainValidHour(rs.getBigDecimal("RAIN_VALID_HOUR"));
                    station.setRainValidMinute(rs.getBigDecimal("RAIN_VALID_MINUTE"));
                    station.setRainWarnDay(rs.getBigDecimal("RAIN_WARN_DAY"));
                    station.setRainWarnHour(rs.getBigDecimal("RAIN_WARN_HOUR"));
                    station.setRainWarnMinute(rs.getBigDecimal("RAIN_WARN_MINUTE"));
                    station.setRiverSensorType(rs.getString("RIVER_SENSOR_TYPE"));
                    station.setRiverValidHigh(rs.getBigDecimal("RIVER_VALID_HIGH"));
                    station.setRiverValidLow(rs.getBigDecimal("RIVER_VALID_LOW"));
                    station.setRiverValidRange(rs.getBigDecimal("RIVER_VALID_RANGE"));
                    station.setRiverWarnHigh(rs.getBigDecimal("RIVER_WARN_HIGH"));
                    station.setRiverWarnLow(rs.getBigDecimal("RIVER_WARN_LOW"));
                    station.setRiverWarnRange(rs.getBigDecimal("RIVER_WARN_RANGE"));
                    station.setTelphone(rs.getString("TELPHONE"));
                    station.setCenter(rs.getString("CENTER"));
                    station.setFlag_hd(rs.getString("FLAG_HD"));
                    station.setBorrow(rs.getString("BORROW"));
                    station.setFlag_rain(rs.getString("FLAG_RAIN"));
                    station.setFlag_water(rs.getString("FLAG_WATER"));
                    station.setOnline(rs.getString("ONLINE"));
                    return station;
                }
            });

            for (RtuStationModel station : stationList) {
                StationManager.getInstance().store(station);
            }
            /**
             * 添加到redis
             */
            sql = "select * from rtu_station a";
            List<Map<String, Object>> stationListMap = baseReadDao.getJdbcTemplate().queryForList(sql);
            for (int i = 0; i < stationListMap.size(); i++) {
                String stcdKey = stationListMap.get(i).get("STCD").toString();
                String stcdOnline = stationListMap.get(i).get("ONLINE") == null ? "0" : stationListMap.get(i).get("ONLINE").toString();
                ValueOperations station = redisTemplate.opsForValue();
                station.set(stcdKey + "Online", stcdOnline);
            }

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    public void setStationFiveConfig() {
        if (baseReadDao == null) {
            baseReadDao = SpringUtils.getBean("baseReadDao");
        }
        redisTemplate = SpringUtils.getBean("redisTemplate");
        String sql = "select * from rtu_five_config where flag='1' ";
        List<Map<String, Object>> fiveStationListMap = baseReadDao.getJdbcTemplate().queryForList(sql);
        for (int i = 0; i < fiveStationListMap.size(); i++) {
            ValueOperations fiveStation = redisTemplate.opsForValue();
            fiveStation.set(fiveStationListMap.get(i).get("stcd8") + "FiveConfig", "1");
        }
    }

    public void handlerYyTel() {
        try {
            logger.debug(">> 读取redis 燕禹设置电话号码！" + formatter.format(new Date()));

            redisTemplate = SpringUtils.getBean("redisTemplate");
            if (redisTemplate.opsForList().size("YyTel") > 0) {
                try {
                    String msg = redisTemplate.opsForList().rightPop("YyTel").toString();
                    String[] listString = msg.split("\\$");
                    String stcd = listString[0];//站号
                    String tel = listString[1];//电话号码
                    String flagHd = listString[2];//是否有宏电
                    String center = listString[3];//中心站号
                    String borrow = listString[4];//借位的站号

                    MessageYyConsumer messageYyConsumer = new MessageYyConsumer();
                    messageYyConsumer.setYyTel(stcd, tel, flagHd, center, borrow);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void handlerUpdateSl651F0() {
        try {
            if (baseReadDao == null) {
                baseReadDao = SpringUtils.getBean("baseReadDao");
            }
            MessageSl651Consumer messageSl651Consumer = new MessageSl651Consumer();
            String sqlStation = "select * from rtu_station";
            List<Map<String, Object>> stations = baseReadDao.getJdbcTemplate().queryForList(sqlStation);
            for (Map<String, Object> item : stations) {
                String stcd = item.get("stcd").toString();
                redisTemplate = SpringUtils.getBean("redisTemplate");
                ValueOperations station = redisTemplate.opsForValue();
                String stcdPwd = station.get(stcd + "pwd") == null ? "" : station.get(stcd + "pwd").toString();
                if (StringUtils.isNotBlank(stcdPwd)) {
                    String[] listString = stcdPwd.split("#");
                    String f01 = listString[0];//中心站地址
                    String f03 = listString[1];//密码
                    messageSl651Consumer.setCenterPwd(stcd, f01, f03);
                    logger.debug(">> 读取redis Sl651中心站地址及密码！" + formatter.format(new Date()));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void handlerDeleteData() {
        if (baseDao == null) {
            baseDao = SpringUtils.getBean("baseDao");
        }
        logger.debug(">> 清理报文数据 ！" + formatter.format(new Date()));
        Date tm = new Date();
        Integer day;//获取配置要保留数据的天数
        day = Integer.parseInt(Configurer.getStringProperty("dataDay", "365"));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(tm);
        calendar.add(calendar.DATE, -day);//把日期往后增加一天.整数往后推,负数往前移动
        tm = calendar.getTime();   //这个时间就是日期往后推一天的结果
        //获取当前时间，根据需要保留的数据记录数天数来清理数据
        logger.debug(">> 清理的数据时间：" + formatter.format(tm));
        try {
            //清理报文记录
            String sql = "DELETE FROM  rtu_message  where  SENDTIME<=?";
            baseDao.update(sql, new Object[]{tm});
            //优化 报文表
            sql = "OPTIMIZE TABLE rtu_message";
            baseDao.update(sql, null);
            //清理 小时数据记录
            sql = "DELETE FROM  rtu_message_hour  where  SENDTIME<=?";
            baseDao.update(sql, new Object[]{tm});
            //优化小时表
            sql = "OPTIMIZE TABLE  rtu_message_hour";
            baseDao.update(sql, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void handlerYY() {
        logger.debug(">> 读取redis 燕禹！" + formatter.format(new Date()));

        redisTemplate = SpringUtils.getBean("redisTemplate");
        if (redisTemplate.opsForList().size(RecvConstant.YY) > 0) {
            try {
                String content = redisTemplate.opsForList().rightPop(RecvConstant.YY).toString();
                String msg = content.split("\\#")[0];
                String replayMsg = content.split("\\#")[1];
                String ip = content.split("\\#")[2];
                Integer port = Integer.parseInt(content.split("\\#")[3]);
                byte[] bytes = ByteUtils.hexStringToBytes(msg);
//                CommonMessage message = HdMessageDecoder.decode(bytes);//宏电里面的是燕禹的报文，直接存为燕禹的报文内容来解析
                CommonMessage yyMessage = YanyuMessageDecoder.decode(bytes);
                MessageYyConsumer consumer = new MessageYyConsumer();
                consumer.process("GPRS", yyMessage, replayMsg, ip, port);
                logger.debug("燕禹协议处理数据：" + yyMessage);//接收报文后打印日志
                // System.out.println("---       " + msg + "  ----");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    public void handlerSummit() {

        logger.debug(">> 读取redis 西安山脉！" + formatter.format(new Date()));

        redisTemplate = SpringUtils.getBean("redisTemplate");
        if (redisTemplate.opsForList().size(RecvConstant.SUMMIT) > 0) {
            try {
                String content = redisTemplate.opsForList().rightPop(RecvConstant.SUMMIT).toString();
                String msg = content.split("\\#")[0];
                String replayMsg = content.split("\\#")[1];
                String ip = content.split("\\#")[2];
                Integer port = Integer.parseInt(content.split("\\#")[3]);
                MessageSummitConsumer consumer = new MessageSummitConsumer();
                consumer.process("GPRS", msg);
                logger.debug("西安山脉协议处理数据：" + msg);//接收报文后打印日志

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public void handlerYln() {
        logger.debug(">> 读取redis 亿力能！" + formatter.format(new Date()));

        redisTemplate = SpringUtils.getBean("redisTemplate");
        if (redisTemplate.opsForList().size(RecvConstant.YLN) > 0) {
            try {
                String msg = redisTemplate.opsForList().rightPop(RecvConstant.YLN).toString();
                byte[] bytes = ByteUtils.hexStringToBytes(msg);
                CommonMessage message = YlnMessageDecoder.decode(bytes);

                MessageYlnConsumer consumer = new MessageYlnConsumer();
                consumer.process("GPRS", message);
                // System.out.println("---       " + msg + "  ----");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void handlerYf() {
        logger.debug(">> 读取redis 一方！" + formatter.format(new Date()));
        redisTemplate = SpringUtils.getBean("redisTemplate");
        if (redisTemplate.opsForList().size(RecvConstant.YF) > 0) {
            try {
                String msg = redisTemplate.opsForList().rightPop(RecvConstant.YF).toString();
                MessageYfConsumer consumer = new MessageYfConsumer();
                consumer.process("GPRS", msg);
                // System.out.println("---       " + msg + "  ----");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void handlerSl651(String args) {
        //logger.debug(">> 读取redis Sl651！" + formatter.format(new Date()));
        logger.debug(">>args！" + args);
        String msg = "";
        redisTemplate = SpringUtils.getBean("redisTemplate");
        try {
            while (redisTemplate.opsForList().size(RecvConstant.SL651 + args) > 0) {
                Object temp = redisTemplate.opsForList().rightPop(RecvConstant.SL651 + args);
                if (null != temp) {
                    msg = temp.toString();
                    // System.out.println("----------" + redisTemplate.opsForList().size("msg") + "----------");
                    String[] msgList = msg.split("#");
                    String msgInfo = msgList[0];
                    String relayMsg = msgList[1];
                    String ip = msgList[2];
                    Integer port = Integer.parseInt(msgList[3]);
                    int recvPort = Integer.parseInt(msgList[4]);
                    byte[] bytes = ByteUtils.hexStringToBytes(msgInfo);
                    try {
                        CommonMessage message = Sl651MessageDecoder.decodeHex(bytes);
                        MessageSl651Consumer consumer = new MessageSl651Consumer();
                        consumer.processMessage("GPRS", message, relayMsg, ip, port, recvPort);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                    // System.out.println("---       " + msg + "  ----");
                }
            }
        } catch (Exception e) {
            logger.info("-----------------------------定时处理任务处理过程中报错-----------------------------");
            e.printStackTrace();
        } finally {
            RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
        }
    }

    public void handlerSl651F36() {
        //logger.debug(">> 读取redis Sl651！" + formatter.format(new Date()));
        String msg = "";
        try {
            redisTemplate = SpringUtils.getBean("redisTemplate");
            while (redisTemplate.opsForList().size(RecvConstant.SL651 + "F36") > 0) {
                //msg = redisTemplate.opsForList().rightPop(RecvConstant.SL651 + "F36").toString();

                Object temp = redisTemplate.opsForList().rightPop(RecvConstant.SL651 + "F36");
                if (null != temp) {
                    msg = temp.toString();
                    // System.out.println("----------" + redisTemplate.opsForList().size("msg") + "----------");
                    String[] msgList = msg.split("#");
                    String msgInfo = msgList[0];
                    String relayMsg = msgList[1];
                    String ip = msgList[2];
                    Integer port = Integer.parseInt(msgList[3]);
                    int recvPort = Integer.parseInt(msgList[4]);
                    byte[] bytes = ByteUtils.hexStringToBytes(msgInfo);
                    CommonMessage message = Sl651MessageDecoder.decodeHex(bytes);

                    MessageSl651Consumer consumer = new MessageSl651Consumer();
                    consumer.processMessage("GPRS", message, relayMsg, ip, port, recvPort);
                }
                // System.out.println("---       " + msg + "  ----");
            }
        } catch (Exception e) {
            logger.info("-----------------------------定时处理任务处理过程中报错-----------------------------");
            e.printStackTrace();
        } finally {
            RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
        }
    }

    public void handlerSms() throws Exception {
        String phList = Configurer.getStringProperty("send.phone.list", "13401079738");
        String appName = Configurer.getStringProperty("appName");
        String[] ph = phList.split(",");
        Server server = new Server();
        server.copyTo();

        if (server.getMem().getUsed() > 20 && appName.equals("江西")) {
            for (String telephone : ph) {
                SmsUtil.send(telephone, "{\"ad\":\"" + appName + "\"}", telephone, "SMS_171851500", "金水云平台");
            }
            return;
        }

        //N个小时没有数据就发送短信
        try {
            //提取mysql数据 是否库里有记录
            BaseDao baseReadDao = SpringUtils.getBean("baseReadDao");//rtu接收库
            Integer hour = Configurer.getIntProperty("hour.interval");//数据间隔
            Integer hourRow = Configurer.getIntProperty("hour.row");
            Calendar rightNow = Calendar.getInstance();
            rightNow.add(Calendar.HOUR, -hour);
            Date tm = rightNow.getTime();
            String searchSql = "select count(*) as cnt from rtu_message where recvtime>?";
            String hourSql = "select count(*) as cnt from rtu_message_hour where recvtime>?";
            int cnt = 0;
            cnt = baseReadDao.getJdbcTemplate().queryForRowSet(searchSql, new Object[]{tm}).getRow();
            int rowHour = baseReadDao.getJdbcTemplate().queryForRowSet(hourSql, new Object[]{tm}).getRow();
            if (cnt <= hourRow || rowHour <= hourRow) {

                for (String telephone : ph) {
                    SmsUtil.send(telephone, "{\"ad\":\"" + appName + "\"}", telephone, "SMS_171851500", "金水云平台");
                }
            }
        } catch (Exception e) {
            for (String telephone : ph) {
                SmsUtil.send(telephone, "{\"ad\":\"" + appName + "\"}", telephone, "SMS_171851500", "金水云平台");
            }
            e.printStackTrace();
        }
    }

    /**
     * 处理历史五分钟数据
     * lhc 20191028
     */
    public void handlerFiveHourData() {
        try {
            logger.info("-------------提取未处理五分钟数据-----------------------------");
            // 发送时间格式YYMMDDHHmmSS
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// yyyy-MM-dd
            BaseDao dao = SpringUtils.getBean("baseReadDao");//rtu接收库
            //提取前1000条未处理数据
            String sql = "SELECT a.*,b.STCD8 FROM rtu_message_hour a LEFT JOIN rtu_station b ON a.stcd=b.stcd " +
                    "WHERE B.STCD8 IN (SELECT STCD8 FROM RTU_FIVE_CONFIG) AND   A.viewtime>'2020-02-15 08:00:00' " +
                    "and A.viewtime<'2020-03-05 17:00:00'  AND  A.dbflag='0' and DATE_FORMAT(viewtime,'%i:%s')='00:00'   order by viewtime LIMIT 1000  ";
            List<Map<String, Object>> fiveConfigList = getFiveConfig();
            MessageSl651Consumer messageSl651Consumer = new MessageSl651Consumer();
            List<RtuHourData> rtuHourDataList = dao.getJdbcTemplate().query(sql,
                    new RowMapper<RtuHourData>() {
                        public RtuHourData mapRow(ResultSet rs, int rowNum) throws SQLException {
                            RtuHourData rtuHourData = new RtuHourData();
                            rtuHourData.setId(rs.getString("ID"));
                            rtuHourData.setValtage(rs.getString("VOLTAGE"));
                            rtuHourData.setStcd(rs.getString("STCD"));
                            rtuHourData.setStcd8(rs.getString("STCD8"));
                            rtuHourData.setViewtime(rs.getString("VIEWTIME"));
                            rtuHourData.setSendtime(rs.getString("SENDTIME"));
                            rtuHourData.setFunccode(rs.getString("FUNCCODE"));
                            rtuHourData.setP05(rs.getString("P05") == null ? "" : rs.getObject("P05").toString());
                            rtuHourData.setP10(rs.getString("P10") == null ? "" : rs.getObject("P10").toString());
                            rtuHourData.setP15(rs.getString("P15") == null ? "" : rs.getObject("P15").toString());
                            rtuHourData.setP20(rs.getString("P20") == null ? "" : rs.getObject("P20").toString());
                            rtuHourData.setP25(rs.getString("P25") == null ? "" : rs.getObject("P25").toString());
                            rtuHourData.setP30(rs.getString("P30") == null ? "" : rs.getObject("P30").toString());
                            rtuHourData.setP35(rs.getString("P35") == null ? "" : rs.getObject("P35").toString());
                            rtuHourData.setP40(rs.getString("P40") == null ? "" : rs.getObject("P40").toString());
                            rtuHourData.setP45(rs.getString("P45") == null ? "" : rs.getObject("P45").toString());
                            rtuHourData.setP50(rs.getString("P50") == null ? "" : rs.getObject("P50").toString());
                            rtuHourData.setP55(rs.getString("P55") == null ? "" : rs.getObject("P55").toString());
                            rtuHourData.setP60(rs.getString("P60") == null ? "" : rs.getObject("P60").toString());
                            rtuHourData.setH05(rs.getString("H05") == null ? "" : rs.getObject("H05").toString());
                            rtuHourData.setH10(rs.getString("H10") == null ? "" : rs.getObject("H10").toString());
                            rtuHourData.setH15(rs.getString("H15") == null ? "" : rs.getObject("H15").toString());
                            rtuHourData.setH20(rs.getString("H20") == null ? "" : rs.getObject("H20").toString());
                            rtuHourData.setH25(rs.getString("H25") == null ? "" : rs.getObject("H25").toString());
                            rtuHourData.setH30(rs.getString("H30") == null ? "" : rs.getObject("H30").toString());
                            rtuHourData.setH35(rs.getString("H35") == null ? "" : rs.getObject("H35").toString());
                            rtuHourData.setH40(rs.getString("H40") == null ? "" : rs.getObject("H40").toString());
                            rtuHourData.setH45(rs.getString("H45") == null ? "" : rs.getObject("H45").toString());
                            rtuHourData.setH50(rs.getString("H50") == null ? "" : rs.getObject("H50").toString());
                            rtuHourData.setH55(rs.getString("H55") == null ? "" : rs.getObject("H55").toString());
                            rtuHourData.setH60(rs.getString("H60") == null ? "" : rs.getObject("H60").toString());
                            return rtuHourData;
                        }
                    });
            logger.info("-------------提取未处理五分钟数据完成-----------------------------");
            //循环处理到五分钟数据，并添加处理完成标志
            for (RtuHourData item : rtuHourDataList) {
                try {
                    Map<String, Object> stcdConfig = new HashMap<>();
                    stcdConfig.put("STCD8", item.getStcd8());
                    stcdConfig.put("FLAG", "1");
                    if (fiveConfigList.contains(stcdConfig)) {
                        logger.info("-------------处理单条记录-----------------------------");
                        messageSl651Consumer.writeSL651FiveData(item.getStcd(), item.getFunccode(), sdf.parse(item.getViewtime()), new Double(item.getValtage()).doubleValue(), "",
                                new String[]{item.getP05(), item.getP10(), item.getP15(), item.getP20(), item.getP25(), item.getP30(), item.getP35(), item.getP40(), item.getP45(), item.getP50(), item.getP55(), item.getP60()},
                                new String[]{item.getH05(), item.getH10(), item.getH15(), item.getH20(), item.getH25(), item.getH30(), item.getH35(), item.getH40(), item.getH45(), item.getH50(), item.getH55(), item.getH60()});

                    } else {
                        logger.info("五分钟数据处理不包含站点" + item.getStcd8());
                    }
                    //设置已经处理完成字段
                    item.setDbFlag("1");
                } catch (Exception ex) {
                    item.setDbFlag("2");
                    ex.printStackTrace();
                    continue;
                }
            }
            logger.info("-------------插入五分钟数据到临时表完成-----------------------------");
            //循环更新状态
            for (RtuHourData item : rtuHourDataList) {
                String updateSql = "update rtu_message_hour set dbflag =? where id=?";
                dao.update(updateSql, new Object[]{item.getDbFlag(), item.getId()});
            }
            logger.info("-------------五分钟数据状态更新完成-----------------------------");
        } catch (Exception e) {
            logger.info("-------------五分钟处理异常-----------------------------");
            e.printStackTrace();
        }
    }

    //提取五分钟配置表
    List<Map<String, Object>> getFiveConfig() {
        BaseDao baseReadDao = SpringUtils.getBean("baseReadDao");//rtu接收库
        String sql = "select * from rtu_five_config where flag='1' ";
        List<Map<String, Object>> fiveConfigList = baseReadDao.getJdbcTemplate().queryForList(sql);
        return fiveConfigList;
    }

    /**
     * 处理历史报文
     * lhc 20191028
     */
    public void handlerMessageData() throws Exception {
        logger.info("-------------提取未处理五分钟数据-----------------------------");
        // 发送时间格式YYMMDDHHmmSS
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// yyyy-MM-dd
        BaseDao baseReadDao = SpringUtils.getBean("baseReadDao");//rtu接收库
        String sql = "SELECT * from rtu_message_hour20190710hour where flag='0' LIMIT 100 ";
        List<Map<String, Object>> messageList = baseReadDao.getJdbcTemplate().queryForList(sql);
        List<Map<String, Object>> ids = new ArrayList<>();
        for (Map<String, Object> list : messageList) {
            Map<String, Object> id = new HashMap<>();
            id.put("ID", list.get("ID").toString());
            try {
                String msgInfo = list.get("MESSAGE").toString();
                String relayMsg = list.get("replaymsg").toString();
                String ip = list.get("srcip").toString();
                Integer port = Integer.parseInt(list.get("srcport").toString());
                byte[] bytes = ByteUtils.hexStringToBytes(msgInfo);
                CommonMessage message = Sl651MessageDecoder.decodeHex(bytes);
                MessageSl651Consumer consumer = new MessageSl651Consumer();
                consumer.processMessage("GPRS", message, relayMsg, ip, port, 0);
                id.put("FLAG", "1");
                ids.add(id);
            } catch (Exception ex) {
                id.put("FLAG", "2");
                ids.add(id);
                ex.printStackTrace();
                continue;
            }
        }
        for (Map<String, Object> id : ids) {
            String updateSql = "update rtu_message_hour20190710hour set flag =? where id=?";
            baseReadDao.update(updateSql, new Object[]{id.get("FLAG").toString(), id.get("ID").toString()});
        }
    }

    /**
     * 重新处理报文异常数据
     * lhc 20191028
     */
    public void handlerInDbMessageData() throws Exception {
        logger.info("-------------重新处理报文异常数据-----------------------------");
        // 发送时间格式YYMMDDHHmmSS
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// yyyy-MM-dd
        BaseDao baseReadDao = SpringUtils.getBean("baseReadDao");//rtu接收库
        String sql = "SELECT * FROM rtu_message WHERE DATE_ADD(NOW(),INTERVAL -1 MONTH ) AND flag='0'";
        List<Map<String, Object>> messageList = baseReadDao.getJdbcTemplate().queryForList(sql);
        List<Map<String, Object>> ids = new ArrayList<>();
        logger.info("-------------获取报文数据-----------------------------" + messageList.size());
        for (Map<String, Object> list : messageList) {
            logger.info("-------------开始处理报文数据-----------------------------");
            Map<String, Object> id = new HashMap<>();
            id.put("ID", list.get("ID").toString());
            try {
                String msgInfo = list.get("MESSAGE").toString();
                String relayMsg = list.get("replaymsg").toString();
                String ip = list.get("srcip").toString();
                Integer port = Integer.parseInt(list.get("srcport") == null ? "0" : list.get("srcport").toString());
                Integer recvport = Integer.parseInt(list.get("recvport") == null ? "0" : list.get("recvport").toString());
                byte[] bytes = ByteUtils.hexStringToBytes(msgInfo);
                CommonMessage message = Sl651MessageDecoder.decodeHex(bytes);
                MessageSl651Consumer consumer = new MessageSl651Consumer();
                consumer.processMessage("GPRS", message, relayMsg, ip, port, recvport);
                id.put("FLAG", "1");
                ids.add(id);
            } catch (Exception ex) {
                id.put("FLAG", "2");
                ids.add(id);
                ex.printStackTrace();
                continue;
            }
        }
        logger.info("-------------结束处理报文数据-----------------------------");
        logger.info("-------------更新处理报文数据状态-----------------------------");
        for (Map<String, Object> id : ids) {
            String updateSql = "update rtu_message set flag =? where id=?";
            baseReadDao.update(updateSql, new Object[]{id.get("FLAG").toString(), id.get("ID").toString()});
        }
        logger.info("-------------结束更新处理报文数据状态-----------------------------");
    }

    /**
     * 定时处理表
     * lhc 20230628
     */
    public void handlerMessageTable() throws Exception {
        //重命名表
        logger.info("-------------重命名表-----------------------------");
        if (baseDao == null) {
            baseDao = SpringUtils.getBean("baseDao");
        }
        //取出当前月日
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
        Date date = new Date(System.currentTimeMillis());
        String tmString = formatter.format(date);
        //System.out.println(formatter.format(date));
        //原始报文表
        String[] sql = {
                "ALTER TABLE rtu_message RENAME TO rtu_message_" + tmString + ";",
                "CREATE TABLE `rtu_message` (\n" +
                        "  `id` VARCHAR(64) NOT NULL,\n" +
                        "  `stcd` VARCHAR(12) NOT NULL,\n" +
                        "  `protocol` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `sendtime` DATETIME DEFAULT NULL,\n" +
                        "  `recvtime` DATETIME NOT NULL,\n" +
                        "  `channel` VARCHAR(20) DEFAULT NULL,\n" +
                        "  `message` VARCHAR(5000) DEFAULT NULL,\n" +
                        "  `funccode` VARCHAR(2) DEFAULT NULL,\n" +
                        "  `serial` DECIMAL(9,0) DEFAULT NULL,\n" +
                        "  `mamount` DECIMAL(9,0) DEFAULT NULL,\n" +
                        "  `mseq` DECIMAL(9,0) DEFAULT NULL,\n" +
                        "  `flag` DECIMAL(9,0) DEFAULT NULL,\n" +
                        "  `voltage` DECIMAL(19,2) DEFAULT NULL,\n" +
                        "  `replaymsg` VARCHAR(5000) DEFAULT NULL,\n" +
                        "  `srcip` VARCHAR(50) DEFAULT NULL,\n" +
                        "  `srcport` VARCHAR(50) DEFAULT NULL,\n" +
                        "  `recvport` VARCHAR(50) DEFAULT NULL,\n" +
                        "  `stnm` VARCHAR(12) DEFAULT NULL,\n" +
                        "  `sttp` VARCHAR(12) DEFAULT NULL,\n" +
                        "  `stcd8` VARCHAR(12) DEFAULT NULL,\n" +
                        "  PRIMARY KEY (`id`)\n" +
                        ") ENGINE=MYISAM DEFAULT CHARSET=utf8 ;",
                "ALTER TABLE `rtu_message` ADD INDEX index_stcd(`stcd`)",
                "ALTER TABLE `rtu_message` ADD INDEX index_recvtime(`recvtime`)",
                "ALTER TABLE `rtu_message` ADD INDEX index_sendtime(`sendtime`)",
                "ALTER TABLE `rtu_message` ADD INDEX index_stcd8(`stcd8`)",
                "ALTER TABLE `rtu_message` ADD INDEX index_funccode(`funccode`)",
                /*小时表*/
                "ALTER TABLE rtu_message_hour RENAME TO rtu_message_hour_" + tmString + ";",
                "CREATE TABLE `rtu_message_hour` (\n" +
                        "  `id` VARCHAR(64) NOT NULL,\n" +
                        "  `mid` VARCHAR(64) DEFAULT NULL,\n" +
                        "  `stcd` VARCHAR(20) NOT NULL,\n" +
                        "  `funccode` VARCHAR(4) DEFAULT NULL,\n" +
                        "  `viewtime` DATETIME DEFAULT NULL,\n" +
                        "  `sendtime` DATETIME DEFAULT NULL,\n" +
                        "  `recvtime` DATETIME NOT NULL,\n" +
                        "  `voltage` DECIMAL(8,2) DEFAULT NULL,\n" +
                        "  `channel` VARCHAR(20) DEFAULT NULL,\n" +
                        "  `p05` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p10` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p15` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p20` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p25` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p30` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p35` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p40` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p45` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p50` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p55` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `p60` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h05` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h10` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h15` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h20` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h25` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h30` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h35` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h40` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h45` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h50` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h55` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `h60` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `f26` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `f20` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `f1a` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `f37` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `f39` VARCHAR(20) DEFAULT NULL,\n" +
                        "  `f3c` VARCHAR(10) DEFAULT NULL,\n" +
                        "  `dbflag` VARCHAR(1) DEFAULT '0',\n" +
                        "  `sttp` VARCHAR(255) DEFAULT NULL,\n" +
                        "  `stcd8` VARCHAR(8) DEFAULT NULL,\n" +
                        "  `stnm` VARCHAR(12) DEFAULT NULL,\n" +
                        "  `f10`  VARCHAR(50) DEFAULT NULL COMMENT 'f10',\n" +
                        "  `f11`  VARCHAR(50) DEFAULT NULL COMMENT 'f11',\n" +
                        "  `f13`  VARCHAR(50) DEFAULT NULL COMMENT 'f13',\n" +
                        "  `f0d`  VARCHAR(50) DEFAULT NULL COMMENT 'f0d',\n" +
                        "  `f06`  VARCHAR(50) DEFAULT NULL COMMENT 'f06',\n" +
                        "  `f07`  VARCHAR(50) DEFAULT NULL COMMENT 'f07',\n" +
                        "  `fa3`  VARCHAR(50) DEFAULT NULL COMMENT 'fa3',\n" +
                        "  `fa4`  VARCHAR(50) DEFAULT NULL COMMENT 'fa4',\n" +
                        "  `f02`  VARCHAR(50) DEFAULT NULL COMMENT 'f02',\n" +
                        "  `f18`  VARCHAR(50) DEFAULT NULL COMMENT 'f18',\n" +
                        "  `f45`  VARCHAR(50) DEFAULT NULL COMMENT 'f45',\n" +
                        "  `f27`  VARCHAR(50) DEFAULT NULL COMMENT 'f27',\n" +
                        "  PRIMARY KEY (`id`)\n" +
                        ") ENGINE=MYISAM DEFAULT CHARSET=utf8",
                "ALTER TABLE `rtu_message_hour` ADD INDEX index_funccode(`funccode`);",
                "ALTER TABLE `rtu_message_hour` ADD INDEX index_viewtime(`viewtime`);",
                "ALTER TABLE `rtu_message_hour` ADD INDEX index_recvtime(`recvtime`);",
                "ALTER TABLE `rtu_message_hour` ADD INDEX index_stcd8(`stcd8`);",
                "ALTER TABLE `rtu_message_hour` ADD INDEX index_stcd(`stcd`);",
                /*到报率表*/
                "ALTER TABLE rtu_rate RENAME TO rtu_rate_" + tmString + ";",
                "CREATE TABLE `rtu_rate` (\n" +
                        "  `stcd` VARCHAR(12) NOT NULL,\n" +
                        "  `tm` DATETIME NOT NULL,\n" +
                        "  `flag` DECIMAL(1,0) DEFAULT '0',\n" +
                        "  `gprs` INT(2) DEFAULT NULL,\n" +
                        "  `gsm` INT(2) DEFAULT NULL,\n" +
                        "  `bd` INT(2) DEFAULT NULL,\n" +
                        "  `pstn` INT(2) DEFAULT NULL,\n" +
                        "  `channel` VARCHAR(255) DEFAULT NULL,\n" +
                        "  PRIMARY KEY (`stcd`,`tm`)\n" +
                        ") ENGINE=MYISAM DEFAULT CHARSET=utf8;",
                "ALTER TABLE `rtu_rate` ADD INDEX index_stcd(`stcd`);",
                "ALTER TABLE `rtu_rate` ADD INDEX index_tm(`tm`);",
                /*图片表*/
                "ALTER TABLE rtu_message_img RENAME TO rtu_message_img_" + tmString + ";",
                "CREATE TABLE `rtu_message_img` (\n" +
                        "  `ID` varchar(64) NOT NULL,\n" +
                        "  `STCD` varchar(12) NOT NULL,\n" +
                        "  `VIEWTIME` datetime DEFAULT NULL,\n" +
                        "  `SENDTIME` datetime DEFAULT NULL,\n" +
                        "  `SAVEPATH` varchar(500) DEFAULT NULL,\n" +
                        "  `SAVENAME` varchar(50) DEFAULT NULL,\n" +
                        "  `SAVETIME` datetime DEFAULT NULL,\n" +
                        "  `DBFLAG` varchar(1) DEFAULT '0',\n" +
                        "  `sttp` varchar(255) DEFAULT NULL,\n" +
                        "  PRIMARY KEY (`ID`),\n" +
                        "  KEY `VIEWTIME` (`VIEWTIME`,`SENDTIME`,`STCD`)\n" +
                        ") ENGINE=MYISAM DEFAULT CHARSET=utf8;",
                /*测试表*/
                "ALTER TABLE rtu_message_test RENAME TO rtu_message_test_" + tmString + ";",
                "CREATE TABLE `rtu_message_test` (\n" +
                        "  `ID` varchar(64) NOT NULL,\n" +
                        "  `MID` varchar(64) DEFAULT NULL,\n" +
                        "  `STCD` varchar(20) DEFAULT NULL,\n" +
                        "  `FUNCCODE` varchar(4) DEFAULT NULL,\n" +
                        "  `VIEWTIME` datetime DEFAULT NULL,\n" +
                        "  `SENDTIME` datetime DEFAULT NULL,\n" +
                        "  `RECVTIME` datetime DEFAULT NULL,\n" +
                        "  `VOLTAGE` decimal(8,2) DEFAULT NULL,\n" +
                        "  `CHANNEL` varchar(20) DEFAULT NULL,\n" +
                        "  `P05` varchar(10) DEFAULT NULL,\n" +
                        "  `P10` varchar(10) DEFAULT NULL,\n" +
                        "  `P15` varchar(10) DEFAULT NULL,\n" +
                        "  `P20` varchar(10) DEFAULT NULL,\n" +
                        "  `P25` varchar(10) DEFAULT NULL,\n" +
                        "  `P30` varchar(10) DEFAULT NULL,\n" +
                        "  `P35` varchar(10) DEFAULT NULL,\n" +
                        "  `P40` varchar(10) DEFAULT NULL,\n" +
                        "  `P45` varchar(10) DEFAULT NULL,\n" +
                        "  `P50` varchar(10) DEFAULT NULL,\n" +
                        "  `P55` varchar(10) DEFAULT NULL,\n" +
                        "  `P60` varchar(10) DEFAULT NULL,\n" +
                        "  `H05` varchar(10) DEFAULT NULL,\n" +
                        "  `H10` varchar(10) DEFAULT NULL,\n" +
                        "  `H15` varchar(10) DEFAULT NULL,\n" +
                        "  `H20` varchar(10) DEFAULT NULL,\n" +
                        "  `H25` varchar(10) DEFAULT NULL,\n" +
                        "  `H30` varchar(10) DEFAULT NULL,\n" +
                        "  `H35` varchar(10) DEFAULT NULL,\n" +
                        "  `H40` varchar(10) DEFAULT NULL,\n" +
                        "  `H45` varchar(10) DEFAULT NULL,\n" +
                        "  `H50` varchar(10) DEFAULT NULL,\n" +
                        "  `H55` varchar(10) DEFAULT NULL,\n" +
                        "  `H60` varchar(10) DEFAULT NULL,\n" +
                        "  `F26` varchar(10) DEFAULT NULL,\n" +
                        "  `F20` varchar(10) DEFAULT NULL,\n" +
                        "  `F1A` varchar(10) DEFAULT NULL,\n" +
                        "  `F37` varchar(10) DEFAULT NULL,\n" +
                        "  `F39` varchar(10) DEFAULT NULL,\n" +
                        "  `DBFLAG` varchar(1) DEFAULT '0',\n" +
                        "  `F3C` varchar(10) DEFAULT NULL,\n" +
                        "  `stcd8` varchar(8) DEFAULT NULL,\n" +
                        "  `stnm` varchar(12) DEFAULT NULL,\n" +
                        "  `sttp` varchar(12) DEFAULT NULL,\n" +
                        "  `f10`  VARCHAR(50) DEFAULT NULL COMMENT 'f10',\n" +
                        "  `f11`  VARCHAR(50) DEFAULT NULL COMMENT 'f11',\n" +
                        "  `f13`  VARCHAR(50) DEFAULT NULL COMMENT 'f13',\n" +
                        "  `f0d`  VARCHAR(50) DEFAULT NULL COMMENT 'f0d',\n" +
                        "  `f06`  VARCHAR(50) DEFAULT NULL COMMENT 'f06',\n" +
                        "  `f07`  VARCHAR(50) DEFAULT NULL COMMENT 'f07',\n" +
                        "  `fa3`  VARCHAR(50) DEFAULT NULL COMMENT 'fa3',\n" +
                        "  `fa4`  VARCHAR(50) DEFAULT NULL COMMENT 'fa4',\n" +
                        "  `f02`  VARCHAR(50) DEFAULT NULL COMMENT 'f02',\n" +
                        "  `f18`  VARCHAR(50) DEFAULT NULL COMMENT 'f18',\n" +
                        "  `f45`  VARCHAR(50) DEFAULT NULL COMMENT 'f45',\n" +
                        "  `f27`  VARCHAR(50) DEFAULT NULL COMMENT 'f27',\n" +
                        "  PRIMARY KEY (`ID`),\n" +
                        "  KEY `rtu_message_test_index` (`STCD`,`VIEWTIME`,`SENDTIME`)\n" +
                        ") ENGINE=MYISAM DEFAULT CHARSET=utf8;",
                /*告警表*/
                "ALTER TABLE rtu_alarm RENAME TO rtu_alarm_" + tmString + ";",
                "CREATE TABLE `rtu_alarm` (\n" +
                        "  `ID` int(11) NOT NULL AUTO_INCREMENT,\n" +
                        "  `STCD` varchar(12) NOT NULL,\n" +
                        "  `TYPE` varchar(10) DEFAULT NULL COMMENT '系统消息，告警消息(WARN)',\n" +
                        "  `SOURCE` varchar(10) DEFAULT NULL COMMENT '数据超警、范围值校验等',\n" +
                        "  `DTIME` datetime DEFAULT NULL,\n" +
                        "  `SENDTM` datetime DEFAULT NULL,\n" +
                        "  `CONTENT` varchar(200) DEFAULT NULL,\n" +
                        "  `FLAG` varchar(1) DEFAULT '0' COMMENT '是否已读标记',\n" +
                        "  PRIMARY KEY (`ID`)\n" +
                        ") ENGINE=MYISAM AUTO_INCREMENT=44893682 DEFAULT CHARSET=utf8;"

        };
        baseDao.batchUpdate(sql);
        System.out.println("CS");
    }

    public static void main(String[] args) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
        Date date = new Date(System.currentTimeMillis());
        System.out.println(formatter.format(date));
        String tableName = "rtu_message_" + formatter.format(date);
        System.out.println(tableName);
    }

}
